package com.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset=utf-8");
        String method = req.getParameter("method");
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();
        PrintWriter out = resp.getWriter();
        JsonUtil jsonUtil = new JsonUtil();

        if (method!=null && !method.equals("")){
            try {
                Method method1 = this.getClass().getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
                method1.invoke(this,req,resp);

            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                jsonUtil.setCode(1);
                jsonUtil.setMsg("未找到该方法");
                out.print(gson.toJson(jsonUtil));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                jsonUtil.setCode(1);
                jsonUtil.setMsg("根据您传递的参数"+method+"无法调用"+this.getClass().getName()+"类中方法，请检查该方法是否为public修饰的");
                out.print(gson.toJson(jsonUtil));
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                jsonUtil.setCode(1);
                jsonUtil.setMsg("根据您传递的参数method"+method+"调用"+this.getClass().getName()+"类该方法出现了异常"+e.getMessage());
                out.print(gson.toJson(jsonUtil));
            }


        }else {
            jsonUtil.setCode(1);
            jsonUtil.setMsg("请求参数中未包含method的参数");
            out.print(gson.toJson(jsonUtil));
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
